﻿using System;
using System.Data;
using SubSonic;

namespace Medianamik.Core.Sugar.IdentityGenerator
{
    public static class IdentityGenerator
    {
        public static int GetNextIdentity(this string key, int? startingValue)
        {
            var identity = SPs.GetNextIdentityForKey(key, startingValue).ExecuteScalar() as int?;

            if (!identity.HasValue)
                throw new Exception("Can't get a new identity value.");

            return identity.Value;
        }
    }

    public static class SPs
    {
        public static StoredProcedure GetNextIdentityForKey(string key, int? startingValue)
        {
            var sp = new StoredProcedure("medianamik_GetNextIdentityForKey", DataService.GetInstance("MedianamikProvider"), "dbo");

            sp.Command.AddParameter("@key", key, DbType.AnsiString, null, null);

            sp.Command.AddParameter("@startingValue", startingValue, DbType.Int32, null, null);

            return sp;
        }

    }
}